<template>
  <div
    class="app-container"
    style="height: 100%"
    v-loading="loading"
    element-loading-text="加载中..."
  >
    <el-container class="main">
      <el-aside width="310px">
        <el-card class="box-card">
          <div class="card_user">
            <el-image :src="userInfo?.avatar" fit="contain" class="img_user">
              <template #error>
                <div class="image-slot">
                  <el-icon>
                    <Avatar />
                  </el-icon>
                </div>
              </template>
            </el-image>
            <div>
              <p class="name">昵称：{{ userInfo?.name }}</p>
              <p class="phone">账号：{{ userInfo?.phone }}</p>
            </div>
            <ul class="ul_list">
              <li class="li_list">
                <el-icon class="li_icon" size="24">
                  <Check />
                </el-icon>
                <div class="li_right">
                  <p class="num">{{ userInfo?.productNo }}</p>
                  <p class="type">关联产品</p>
                </div>
              </li>
              <li class="li_list">
                <el-icon class="li_icon" size="24">
                  <Check />
                </el-icon>
                <div class="li_right">
                  <p class="num">{{ userInfo?.orderNo }}</p>
                  <p class="type">关联工单</p>
                </div>
              </li>
            </ul>
          </div>

          <div class="header">
            <h6>基本信息</h6>
          </div>
          <el-form label-width="90px" class="form_list">
            <el-form-item label="客户编码：">
              <span>{{ userInfo?.code }}</span>
            </el-form-item>
            <el-form-item label="客户分类：">
              <span>{{ userInfo?.userType }}</span>
            </el-form-item>
            <el-form-item label="知识库权限：">
              <template v-if="userInfo?.selectKnowledgeAuthor">按客户分类权限查看</template>
              <template v-else>查看所有</template>
            </el-form-item>
            <el-form-item label="绑定手机：">
              <span>{{ userInfo?.phone }}</span>
            </el-form-item>
            <el-form-item label="注册时间：">
              <span>{{ userInfo?.createTime }}</span>
            </el-form-item>
            <el-form-item label="更新时间：">
              <span>{{ userInfo?.updateTime }}</span>
            </el-form-item>
            <el-form-item label="最后登录：">
              <span>{{ userInfo?.lastLoginTime }}</span>
            </el-form-item>
          </el-form>
          <div class="btn_edit">
            <HPlainButton @click="editInfo">编辑</HPlainButton>
          </div>
        </el-card>
      </el-aside>

      <!-- 联系人列表信息 -->
      <el-main>
        <div class="list_tabs">
          <el-tabs v-model="activeName" class="tabs_height">
            <el-tab-pane label="联系人" name="first">
              <div style="display: flex; justify-content: space-between">
                <div style="display: flex; gap: 5px">
                  <HPlainButton @click.stop="addLineData">新增联系人</HPlainButton>
                  <HPlainButton @click="deleAll" :disabled="userContactBatchDelBtn" type="error">
                    批量删除
                  </HPlainButton>
                </div>
                <div style="display: flex; gap: 5px">
                  <el-input
                    v-model="name"
                    placeholder="客户名称"
                    clearable
                    class="input-width mr5"
                    @keyup.enter="getList"
                    @clear="getList"
                  />
                  <el-input
                    v-model="telphone"
                    placeholder="客户手机号"
                    clearable
                    class="input-width mr5"
                    @keyup.enter="getList"
                    @clear="getList"
                  />
                  <HButton type="primary" @click="getList">
                    <el-icon>
                      <Search />
                    </el-icon>
                    搜索
                  </HButton>
                </div>
              </div>
              <div class="table">
                <el-table
                  stripe
                  resizable
                  :border="true"
                  :data="selfData"
                  height="100%"
                  ref="selfDom"
                  @selection-change="getCheckbox"
                  style="position: absolute"
                >
                  <!-- 选择 -->
                  <el-table-column
                    type="selection"
                    width="35px"
                    :selectable="checkDisable"
                    align="center"
                  />

                  <!-- 序号 -->
                  <el-table-column label="序号" type="index" width="50px" fixed align="center" />

                  <!-- 联系人姓名 -->
                  <el-table-column prop="name" label="联系人姓名" width="140px">
                    <template v-slot="item">
                      <div v-if="item.row.isEditUserContact">
                        <el-input
                          clearable
                          v-model.trim="item.row.username"
                          placeholder="请输入名称"
                        />
                      </div>
                      <div v-else>
                        {{ item.row.username }}
                      </div>
                    </template>
                  </el-table-column>

                  <!-- 联系人手机号 -->
                  <el-table-column prop="phone" label="联系人手机号" width="130px">
                    <template v-slot="item">
                      <div v-if="item.row.isEditUserContact">
                        <el-input
                          v-model.trim="item.row.phone"
                          placeholder="请输入手机号"
                          maxlength="11"
                          clearable
                        />
                      </div>
                      <div v-else>
                        {{ item.row.phone }}
                      </div>
                    </template>
                  </el-table-column>

                  <!-- 主要联系人 -->
                  <el-table-column
                    prop="mainContact"
                    label="主要联系人"
                    width="90px"
                    align="center"
                  >
                    <template v-slot="item">
                      <div style="display: flex; align-items: center; gap: 5px">
                        <el-switch
                          v-model="item.row.mainContact"
                          :disabled="item.row.isMainUser ? true : !item.row.isEditUserContact"
                        />
                        <span v-if="item.row.mainContact">是</span>
                        <span v-else>否</span>
                      </div>
                    </template>
                  </el-table-column>

                  <!-- 邮箱 -->
                  <el-table-column prop="email" label="邮箱" width="180px">
                    <template v-slot="item">
                      <div v-if="item.row.isEditUserContact">
                        <el-input
                          v-model.trim="item.row.email"
                          placeholder="请输入邮箱"
                          clearable
                        />
                      </div>
                      <div v-else>
                        {{ item.row.email }}
                      </div>
                    </template>
                  </el-table-column>

                  <!-- 联系地区 -->
                  <el-table-column
                    show-overflow-tooltip
                    prop="province"
                    label="联系地区"
                    width="240px"
                  >
                    <template v-slot="item">
                      <div v-if="item.row.isEditUserContact">
                        <SingleAddress
                          ref="addrEditRef"
                          :address="{
                            province: item.row.province,
                            city: item.row.city,
                            area: item.row.area,
                            town: item.row.town,
                          }"
                        />
                      </div>
                      <span v-else>
                        {{ item.row.province }} / {{ item.row.city }} / {{ item.row.area }}
                        {{ item.row.town ? ' / ' + item.row.town : '' }}
                      </span>
                    </template>
                  </el-table-column>

                  <!-- 详细地址 -->
                  <el-table-column
                    show-overflow-tooltip
                    prop="address"
                    label="详细地址"
                    width="220px"
                  >
                    <template v-slot="item">
                      <div v-if="item.row.isEditUserContact">
                        <el-input
                          clearable
                          v-model.trim="item.row.address"
                          placeholder="请输入详细地址"
                        />
                      </div>
                      <span v-else>
                        {{ item.row.address }}
                      </span>
                    </template>
                  </el-table-column>

                  <!-- 操作 -->
                  <el-table-column label="操作" fixed="right" width="100px">
                    <template v-slot="item">
                      <el-space :size="0" :spacer="spacer">
                        <HLink
                          v-if="!item.row.isEditUserContact"
                          @click.stop="onUserContainTableEdit(item.row)"
                          >编辑
                        </HLink>
                        <HLink
                          v-if="!item.row.isEditUserContact && !item.row.isMainUser"
                          @click.stop="deleteLineData(item.$index, item.row)"
                          >删除</HLink
                        >
                      </el-space>
                      <el-space v-if="item.row.isEditUserContact" :size="0" :spacer="spacer">
                        <HLink @click.stop="onUserContainTableSave(item.$index, item.row)"
                          >保存</HLink
                        >
                        <HLink @click.stop="onUserContainTableCancel(item.$index, item.row)"
                          >取消</HLink
                        >
                      </el-space>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <div class="footer">
                <Pagination
                  ref="paginDom"
                  :list_total="total"
                  @size-change="getList"
                  @current-change="getList"
                />
              </div>
            </el-tab-pane>

            <el-tab-pane label="关联商品" name="second">
              <div class="table">
                <el-table
                  :border="true"
                  v-if="activeName == 'second'"
                  :data="UserRelationCodeGoodsList?.rows || []"
                  resizable
                  stripe
                  height="100%"
                  style="position: absolute"
                >
                  <template #empty>
                    <el-empty description="暂无数据" />
                  </template>
                  <el-table-column label="序号" width="50">
                    <template v-slot="i">
                      <div>
                        {{ i.$index + 1 }}
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column show-overflow-tooltip label="商品信息">
                    <template v-slot="i">
                      {{ i.row.goodsBrand }}&nbsp;{{ i.row.goodsName }}&nbsp;{{
                        i.row.goodsModel
                      }}&nbsp;{{ i.row.goodsSpecName }}
                    </template>
                  </el-table-column>
                  <el-table-column prop="status" label="状态" width="70">
                    <template #default="scope">
                      <HStatus v-if="scope.row.status !== 2" type="info">禁用</HStatus>
                      <HStatus v-else>启用</HStatus>
                    </template>
                  </el-table-column>
                  <el-table-column prop="code" show-overflow-tooltip label="商品编号" width="180" />
                  <el-table-column
                    prop="registerTime"
                    show-overflow-tooltip
                    label="登记时间"
                    width="128"
                  />
                </el-table>
              </div>
              <div class="footer">
                <Pagination
                  ref="paginationGoods"
                  :list_total="Number(UserRelationCodeGoodsList?.total || 0)"
                  @size-change="getUserRelationCodeGoodsListFun"
                  @current-change="getUserRelationCodeGoodsListFun"
                />
              </div>
            </el-tab-pane>

            <el-tab-pane label="关联工单" name="third">
              <div class="table">
                <el-table
                  :border="true"
                  v-if="activeName == 'third'"
                  :data="UserRelationOrderList?.rows || []"
                  resizable
                  stripe
                  height="100%"
                  style="width: 100%; position: absolute"
                >
                  <template #empty>
                    <el-empty description="暂无数据" />
                  </template>
                  <el-table-column label="序号" width="50">
                    <template v-slot="item">
                      <span> {{ item.$index + 1 }} </span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="workNo"
                    show-overflow-tooltip
                    label="工单编码"
                    width="180"
                  />
                  <el-table-column show-overflow-tooltip prop="status" label="状态" width="118">
                    <template #default="scope">
                      <HStatus type="warning" v-if="scope.row.status === 1">待派单</HStatus>
                      <HStatus type="warning" v-if="scope.row.status === 2">待服务商确认</HStatus>
                      <HStatus type="warning" v-if="scope.row.status === 3">处理中</HStatus>
                      <HStatus type="success" v-if="scope.row.status === 4">已完成</HStatus>
                      <HStatus type="info" v-if="scope.row.status === 5">已取消</HStatus>
                    </template>
                  </el-table-column>
                  <el-table-column show-overflow-tooltip label="商品信息">
                    <template v-slot="i">
                      {{ i.row.goodsBrand }}&nbsp;{{ i.row.goodsName }}&nbsp;{{
                        i.row.goodsModel
                      }}&nbsp;{{ i.row.goodsSpecName }}
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="createTime"
                    show-overflow-tooltip
                    label="创建时间"
                    width="128"
                  />
                  <el-table-column
                    prop="endTime"
                    show-overflow-tooltip
                    label="完成时间"
                    width="128"
                  />
                </el-table>
              </div>
              <div class="footer">
                <Pagination
                  ref="paginationOrder"
                  :list_total="Number(UserRelationOrderList?.total || 0)"
                  @size-change="getUserRelationOrderListFun"
                  @current-change="getUserRelationOrderListFun"
                />
              </div>
            </el-tab-pane>

            <!-- 客户附件 -->
            <el-tab-pane label="客户附件" name="fourth">
              <div class="upload_file">
                <p class="tip_text">上传附件:</p>
                <el-upload
                  :auto-upload="false"
                  drag
                  action="#"
                  :limit="10"
                  accept="image/*,.pdf"
                  multiple
                  :show-file-list="false"
                  :on-change="handleChange"
                >
                  <el-icon class="up_icon"><upload-filled /></el-icon>
                  <div>点击上传图片或者文件</div>
                </el-upload>
                <ul class="ul_list">
                  <li class="li_item" v-for="(it, index) in fileList" :key="index">
                    <div class="li_item_left">
                      <img
                        :src="pdf"
                        @click.stop="lookFile(it.path, '附件')"
                        style="width: 30px; height: 30px; cursor: pointer"
                        alt=""
                        v-if="
                          (it.name
                            ? it.name
                            : it.path.split('/')[it.path.split('/').length - 1]
                          ).replace(/.+\./, '') == 'pdf'
                        "
                      />
                      <el-image
                        v-else
                        :preview-src-list="[it.path]"
                        style="width: 30px; height: 30px"
                        :src="it.path"
                        fit="contain"
                      />
                      <span class="pic_name">{{
                        it.name ? it.name : it.path.split('/')[it.path.split('/').length - 1]
                      }}</span>
                    </div>
                    <el-icon size="16" style="cursor: pointer" @click.stop="deleteItem(index)">
                      <Delete />
                    </el-icon>
                  </li>
                </ul>
                <div class="btns" style="display: flex; gap: 5px">
                  <HPlainButton type="primary" @click="annexSaveSubmit">保存</HPlainButton>
                  <HButton @click="onCancel"> 取消 </HButton>
                </div>
              </div>
            </el-tab-pane>
            <el-tab-pane label="知识库" name="knowledge">
              <div>
                <span>知识库查看权限：</span>
                <el-radio-group
                  v-model="selectKnowledgeAuthor"
                  @change="onUpdateSelectKnowledgeAuthor"
                >
                  <el-radio :value="false" size="large">查看所有</el-radio>
                  <el-radio :value="true" size="large">按客户分类权限查看</el-radio>
                </el-radio-group>
              </div>
              <!-- 知识库分配权限表格内容 -->
              <div v-show="selectKnowledgeAuthor">
                <div style="display: flex; justify-content: flex-end">
                  <HPlainButton @click="openEditUserType">编辑客户分类</HPlainButton>
                </div>
                <div>
                  <el-table
                    :data="knowledgeTableData"
                    border
                    style="width: 100%; margin-top: 12px"
                    height="68vh"
                  >
                    <el-table-column label="序号" type="index" width="55" />
                    <el-table-column prop="userType" label="客户分类" min-width="110" />
                    <el-table-column prop="name" label="知识库类型权限" min-width="110" />
                    <el-table-column prop="createTime" label="创建时间" width="150" />
                    <el-table-column prop="updateTime" label="更新时间" width="150" />
                    <el-table-column label="操作" width="240">
                      <template #default="scope">
                        <el-space :size="0" :spacer="spacer">
                          <HLink @click="viewDetails(scope.row.id, 1)">说明书详情</HLink>
                          <HLink @click="viewDetails(scope.row.id, 2)">故障库详情</HLink>
                          <HLink @click="viewDetails(scope.row.id, 3)">视频详情</HLink>
                        </el-space>
                      </template>
                    </el-table-column>
                  </el-table>
                </div>
              </div>
            </el-tab-pane>
          </el-tabs>
        </div>
      </el-main>
    </el-container>
    <!-- 文件查看 -->
    <el-dialog
      :title="`查看${file.type}`"
      v-model="dialogContract"
      :draggable="true"
      :destroy-on-close="true"
      :close-on-click-modal="false"
    >
      <iframe :src="`${file.file}`" width="100%" height="100%" style="height: 700px"></iframe>
    </el-dialog>

    <!-- 编辑客户弹窗 -->
    <HModal v-model="addDialog" :width="500">
      <template #header>
        <div class="my-header">
          <h3 class="title">{{ userForm.title }}</h3>
        </div>
      </template>
      <div v-loading="addLoading" element-loading-text="加载中...">
        <el-form
          label-width="80px"
          ref="userFormRef"
          :model="userForm"
          :rules="rules"
          @validate="handleEditCustomerFormValidate"
          class="edit_customer_modal_form_content"
        >
          <el-form-item
            label="账号名称"
            prop="name"
            :class="{
              form_item: editCustomerModalFormValidateResult['name'],
              validate_fail: !editCustomerModalFormValidateResult['name'],
            }"
          >
            <el-input
              v-model="userForm.name"
              placeholder="请输入客户名称"
              class="input-width"
              clearable
            />
          </el-form-item>

          <el-form-item
            label="客户账号"
            prop="phone"
            :class="{
              form_item: editCustomerModalFormValidateResult['phone'],
              validate_fail: !editCustomerModalFormValidateResult['phone'],
            }"
          >
            <el-input
              v-model="userForm.phone"
              placeholder="请输入客户手机号"
              class="input-width"
              clearable
              maxlength="11"
            />
          </el-form-item>

          <el-form-item label="客户级别" class="form_item">
            <el-select
              v-model="userForm.levelId"
              placeholder="客户级别"
              filterable
              reserve-keyword
              remote-show-suffix
              :loading="levelLoading"
              :filter-method="searchLevelSelect"
              class="select_item"
            >
              <el-option
                v-for="item in levelOptions"
                @click="changeLevelId(item)"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item
            label="客户分类"
            prop="userTypeId"
            :class="{
              form_item: editCustomerModalFormValidateResult['userTypeId'],
              validate_fail: !editCustomerModalFormValidateResult['userTypeId'],
            }"
          >
            <el-select
              v-model="userForm.userTypeId"
              placeholder="客户分类"
              filterable
              reserve-keyword
              remote-show-suffix
              :loading="typeLoading"
              :filter-method="searchTypeSelect"
              class="select_item"
            >
              <el-option
                v-for="item in typeOptions"
                @click="changeUserTypeId(item)"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="客户编码" class="form_item">
            <el-input v-model="userForm.code" placeholder="如无编码系统自动生成" clearable />
          </el-form-item>

          <el-form-item label="客户状态" class="last_form_item">
            <div style="display: flex; align-items: center; gap: 5px">
              <el-switch v-model="userForm.status" />
              <span v-if="userForm.status">启用</span>
              <span v-else>禁用</span>
            </div>
          </el-form-item>
        </el-form>
      </div>

      <template #footerRight>
        <HButton @click="saveData(userFormRef)" type="primary" isModal>保存</HButton>
        <HButton @click="onEditCustomerModalCancelClick" isModal>取消</HButton>
      </template>
    </HModal>

    <!-- 查看说明书 故障 视频 弹窗 -->
    <el-dialog
      v-model="lookTypeDialog"
      width="80%"
      style="height: 70vh"
      :destroy-on-close="true"
      :title="lookType == 1 ? '查看说明书' : lookType == 2 ? '查看故障库' : '查看视频'"
      :draggable="true"
      class="look-dialog"
    >
      <div v-if="lookTypeDataList.length > 0" class="look_type">
        <div v-if="lookType == 1">
          <div v-for="(i, index) in lookTypeDataList" :key="i.id" class="look_item">
            <div class="look_name">({{ index + 1 }})&nbsp;{{ i.name }}</div>
            <div class="look_img"
              ><el-image
                style="width: 100px; height: 100px"
                :src="i.image"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="[i.image]"
                fit="contain"
                lazy
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon>
                      <Picture />
                    </el-icon>
                  </div> </template></el-image
            ></div>
          </div>
        </div>
        <div v-if="lookType == 2">
          <div v-for="(i, index) in lookTypeDataList" :key="i.id" class="look_item">
            <div class="look_name">({{ index + 1 }})&nbsp;{{ i.name }}</div>
            <div class="look_img">解决方法：{{ i.solution }}</div>
            <div class="look_img">备注：{{ i.content }}</div>
          </div>
        </div>
        <div v-if="lookType == 3">
          <div v-for="(i, index) in lookTypeDataList" :key="i.id" class="look_item">
            <div class="look_name">({{ index + 1 }})&nbsp;{{ i.name }}</div>
            <div class="look_img"
              ><el-image
                style="width: 100px; height: 100px"
                :src="i.image"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="[i.image]"
                fit="contain"
                lazy
              >
                <template #error>
                  <div class="image-slot">
                    <el-icon>
                      <Picture />
                    </el-icon>
                  </div> </template></el-image
            ></div>
            <!-- <div class="look_img"><video :auto-play="false" style="width: 100px; height: 100px" :src="i.image"
                @click="playVideo(i.image)"></video></div> -->
          </div>
        </div>
      </div>
      <el-empty
        v-else
        :description="lookType == 1 ? '暂无说明书' : lookType == 2 ? '暂无故障库' : '暂无视频'"
      />
    </el-dialog>

    <el-dialog :visible="isShow" width="70%" @close="closeDialog">
      <video :src="videoUrl" controls autoplay class="video" width="100%"></video>
    </el-dialog>

    <!-- 编辑客户分类弹窗 -->
    <HModal v-model="usertypeDialogVisible" title="编辑客户分类" size="small">
      <el-form ref="userFormRef_change" :model="userForm">
        <el-form-item label="客户分类">
          <el-select
            v-model="userTypeId"
            class="input-width mr5"
            placeholder="客户分类"
            filterable
            reserve-keyword
            remote-show-suffix
            :loading="typeLoading"
            :filter-method="searchTypeSelect"
          >
            <el-option
              v-for="item in typeOptions"
              @click="changeUserType(item)"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footerRight>
        <HButton is-modal type="primary" @click="saveDataChangeType">保存</HButton>
        <HButton is-modal @click="usertypeDialogVisible = false"> 取消 </HButton>
      </template>
    </HModal>
  </div>
</template>

<script setup lang="ts">
  import Pagination from '@/components/Pagination/index.vue'
  import { ElDivider, ElMessage, ElMessageBox, FormItemProp } from 'element-plus'
  import { ref, onMounted, reactive, watch, markRaw, Ref, h } from 'vue'
  import { useRoute } from 'vue-router'
  import { UploadFilled, Delete, Check } from '@element-plus/icons-vue'
  import type { UploadProps, UploadFile, FormInstance } from 'element-plus'
  import { phone } from '@/utils/validate'
  import SingleAddress from '../../../components/address/singleAddress.vue'
  import {
    levelPageSelect,
    typePageSelect,
    addUser,
    getUserInfo,
    getUserContact,
    saveUserContact,
    deleteContact,
    changeContact,
    updateSelectKnowledgeAuthor,
    getSelectKnowledgeAuthorList,
    getUserRelationOrderList,
    getUserRelationCodeGoodsList,
    getUserAnnex,
    annexSave,
    getInstructionBook,
    getFailt,
    getVideo,
  } from '@/api/users'
  import { userAnnexUpload } from '@/api/upload'
  import { AxiosPromise } from 'axios'
  import pdf from '@/assets/image/pdf.png'
  import * as _ from 'lodash'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
  import HButton from '@/components/common/button/HButton.vue'
  import HLink from '@/components/common/link/HLink.vue'
  import HStatus from '@/components/common/status/HStatus.vue'
  import HModal from '@/components/common/Modal/HModal.vue'
  import pageComponentName from '@/config/page-component-name'

  defineOptions({
    name: pageComponentName.customer.customerDetail,
  })

  // 间距组件的间隔符
  const spacer = h(ElDivider, { direction: 'vertical' })

  const route = useRoute()
  const activeName = ref('first')
  const addDialog = ref(false)
  const loading = ref(false)
  const selectKnowledgeAuthor = ref(false) // 是否根据权限查看知识库：false-查看所有，true-根据权限查看
  const usertypeDialogVisible = ref(false) // 客户分类编辑弹窗
  const userTypeId = ref('') // 客户分类ID
  const userType = ref()
  const paginationOrder = ref()
  const paginationGoods = ref()
  const knowledgeTableData = ref([])
  const userInfo = ref(null) // 客户信息
  const addrEditRef = ref()
  const userContactBatchDelBtn = ref(true) // 联系人批量删除按钮
  const delAnnexIds = ref([]) //图片删除的Id
  const userFormRef_change = ref()
  // 获取客户账号信息
  const getInfo = () => {
    loading.value = true
    getUserInfo(route.params.id).then((res) => {
      userInfo.value = res.data.data.row
      userForm.addrs = {
        province: res.data.data.row.province,
        city: res.data.data.row.city,
        area: res.data.data.row.area,
        town: res.data.data.row.town,
      }
      userForm.address = res.data.data.row.address
      loading.value = false
      userTypeId.value = userInfo.value?.userTypeId === '0' ? '' : userInfo.value?.userTypeId
      userType.value = userInfo.value?.userType
      selectKnowledgeAuthor.value = userInfo.value?.selectKnowledgeAuthor
    })
  }

  watch(activeName, (n) => {
    switch (n) {
      case 'first':
        getList()
        break
      case 'second':
        getUserRelationCodeGoodsListFun()
        break
      case 'third':
        getUserRelationOrderListFun()
        break
      case 'fourth':
        getUserFilt()
        break
      case 'knowledge':
        getKnowledgeAuthorList()
        break
    }
  })
  function closeDialog() {
    // 关闭弹框
    isShow.value = false
    videoUrl.value = '' // 清空数据 关闭视频播放
  }
  // 查看 1说明书 2故障库 3视频
  const lookType = ref()
  const lookTypeDataList = ref()
  const lookTypeDialog = ref(false)
  const videoUrl = ref()
  const isShow = ref(false)
  const viewDetails = _.debounce((id, type) => {
    lookType.value = type
    lookTypeDataList.value = []
    switch (type) {
      case 1:
        getInstructionBook(id).then((res) => {
          if (!res) {
            return
          }
          if (res.data.success) {
            lookTypeDataList.value = res.data.data.row
          } else {
            if (res.data.isError)
              ElMessage({
                message: res.data.message,
                type: 'error',
                duration: 2000,
              })
          }
        })
        break
      case 2:
        getFailt(id).then((res) => {
          if (!res) {
            return
          }
          if (res.data.success) {
            lookTypeDataList.value = res.data.data.row
          } else {
            if (res.data.isError)
              ElMessage({
                message: res.data.message,
                type: 'error',
                duration: 2000,
              })
          }
        })
        break
      case 3:
        getVideo(id).then((res) => {
          if (!res) {
            return
          }
          if (res.data.success) {
            lookTypeDataList.value = res.data.data.row
          } else {
            if (res.data.isError)
              ElMessage({
                message: res.data.message,
                type: 'error',
                duration: 2000,
              })
          }
        })
        break
    }
    lookTypeDialog.value = true
  }, 600)

  onMounted(() => {
    getInfo()
    getList()
  })

  // 下拉数据
  const levelOptions = ref([]) // 级别
  const typeOptions = ref([]) // 分类

  const levelVal = ref('')
  const levelLoading = ref(false)

  const typeVal = ref('')
  const typeLoading = ref(false)

  // 编辑客户分类弹窗
  const openEditUserType = async () => {
    getLevelOptions('')
    getTypeOptions('')
    usertypeDialogVisible.value = true
  }

  const changeUserType = (item) => {
    userType.value = item.name
  }
  // 保存户分类弹窗
  const saveDataChangeType = () => {
    const data = {
      address: userInfo.value.address,
      area: userInfo.value.area,
      city: userInfo.value.city,
      code: userInfo.value.code,
      email: userInfo.value.email,
      id: userInfo.value.id,
      level: userInfo.value.level,
      levelId: userInfo.value.levelId,
      name: userInfo.value.name,
      phone: userInfo.value.phone,
      province: userInfo.value.province,
      status: userInfo.value.status,
      town: userInfo.value.town,
      userType: userType.value,
      userTypeId: userTypeId.value,
    }
    addUser(data).then((res) => {
      if (res.data.isError)
        ElMessage({
          message: res.data.message,
          type: res.data.success ? 'success' : 'error',
          duration: 2000,
        })
      if (res.data.success) {
        usertypeDialogVisible.value = false
        getInfo()
        getKnowledgeAuthorList()
      }
    })
  }
  // 获取分页下拉数据
  const getPageData = (name) => {
    return {
      limit: 0,
      name: name,
      page: 0,
    }
  }

  // 获取级别下拉
  const getLevelOptions = async (name: string) => {
    await levelPageSelect(getPageData(name)).then((res) => {
      levelOptions.value = res.data.data.rows
    })
  }

  // 搜索级别下拉数据
  const searchLevelSelect = _.throttle((query: string) => {
    levelVal.value = query
    if (query) {
      levelLoading.value = true
      setTimeout(async () => {
        levelLoading.value = false
      }, 1000)
    }
  }, 500)

  // 获取分类下拉
  const getTypeOptions = async (name: string) => {
    await typePageSelect(getPageData(name)).then((res) => {
      typeOptions.value = res.data.data.rows
    })
  }

  // 搜索分类下拉数据
  const searchTypeSelect = _.throttle((query: string) => {
    typeVal.value = query
    if (query) {
      typeLoading.value = true
      setTimeout(async () => {
        typeLoading.value = false
      }, 1000)
    }
  }, 500)

  // 更新客户知识库查看权限
  const onUpdateSelectKnowledgeAuthor = (val: boolean) => {
    updateSelectKnowledgeAuthor(route.params.id, { selectKnowledgeAuthor: val }).then((res) => {
      if (res.data.code == 20000) {
        selectKnowledgeAuthor.value = val
        userInfo.value.selectKnowledgeAuthor = val
      }
    })
  }

  // 根据客户分类ID获取知识库类型权限列表
  const getKnowledgeAuthorList = () => {
    getSelectKnowledgeAuthorList(userTypeId.value || '0', { page: 1, limit: 50 }).then((res) => {
      if (res.data.code == 20000) {
        knowledgeTableData.value = res.data.data.rows
      }
    })
  }

  // 监听下拉数据变化时是否进行搜索
  watch(
    () => levelVal.value,
    (newVal) => {
      if (newVal != '') {
        getLevelOptions(newVal)
      } else {
        getLevelOptions('')
      }
    },
  )
  watch(
    () => typeVal.value,
    (newVal) => {
      if (newVal != '') {
        getTypeOptions(newVal)
      } else {
        getTypeOptions('')
      }
    },
  )

  // 客户表单数据
  const userForm = reactive({
    addrs: {
      province: '',
      city: '',
      area: '',
      town: '',
    },
    address: '',
    code: '',
    email: '',
    id: route.params.id,
    level: '',
    levelId: '',
    name: '',
    phone: '',
    status: true,
    title: '',
    userType: '',
    userTypeId: '',
  })

  // 验证规则
  const rules = reactive({
    name: [{ required: true, message: '请输入客户名称', trigger: ['blur', 'change'] }],
    phone: [
      { required: true, message: '请输入手机号', trigger: ['blur', 'change'] },
      { validator: phone(userForm.phone), trigger: ['blur', 'change'] },
    ],
    levelId: [{ required: true, message: '请选择客户级别', trigger: ['change', 'blur'] }],
    userTypeId: [{ required: true, message: '请选择客户分类', trigger: ['change', 'blur'] }],
  })

  const editCustomerModalFormValidateResult = ref({
    name: true,
    phone: true,
    levelId: true,
    userTypeId: true,
  })

  const handleEditCustomerFormValidate = (prop: FormItemProp, isValid: boolean) => {
    editCustomerModalFormValidateResult.value[prop as string] = isValid
  }

  const onEditCustomerModalCancelClick = () => {
    addDialog.value = false
    editCustomerModalFormValidateResult.value = {
      name: true,
      phone: true,
      levelId: true,
      userTypeId: true,
    }
  }

  const addLoading = ref(false)
  const userFormRef = ref<FormInstance>()

  // 编辑信息
  const editInfo = async () => {
    await getLevelOptions('')
    await getTypeOptions('')
    userForm.title = '编辑客户信息'
    addLoading.value = true
    addDialog.value = true
    userForm.name = userInfo.value.name
    userForm.phone = userInfo.value.phone
    userForm.email = userInfo.value.email
    userForm.code = userInfo.value.code
    userForm.status = userInfo.value.status == 0 ? true : false
    userForm.userTypeId = userInfo.value.userTypeId === '0' ? '' : userInfo.value.userTypeId
    userForm.userType = userInfo.value.userType
    userForm.level = userInfo.value.level
    userForm.levelId = userInfo.value.levelId
    if (!typeOptions.value.some((o) => o.id == userInfo.value.userTypeId)) {
      getTypeOptions(userInfo.value.userType)
    }
    addLoading.value = false
  }
  const changeUserTypeId = (item) => {
    userForm.userType = item.name
  }
  const changeLevelId = (item) => {
    userForm.level = item.name
  }
  // 保存客户信息
  const saveData = (formEl: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        saveMethod(addUser, addDialog, addLoading)
      }
    })
  }

  // 保存的方法
  const saveMethod = (
    method: {
      (data: object): AxiosPromise<any>
      (arg0: {
        address: string
        area: any
        city: any
        code: string
        email: string
        id: string | string[]
        level: string
        levelId: string
        name: string
        phone: string
        province: any
        status: number
        town: any
        userType: string
        userTypeId: string
      }): Promise<any>
    },
    dialog: Ref<boolean>,
    load: Ref<boolean>,
  ) => {
    const data = {
      address: userForm.address,
      area: userForm.addrs.area,
      city: userForm.addrs.city,
      code: userForm.code,
      email: userForm.email,
      id: userForm.id,
      level: userForm.level,
      levelId: userForm.levelId,
      name: userForm.name,
      phone: userForm.phone,
      province: userForm.addrs.province,
      status: userForm.status ? 0 : 2,
      town: userForm.addrs.town,
      userType: userForm.userType,
      userTypeId: userForm.userTypeId,
    }
    load.value = true
    method(data).then((res: { data: { success: boolean; message: any; isError: boolean } }) => {
      load.value = false
      if (res.data.isError)
        ElMessage({
          message: res.data.message,
          type: res.data.success ? 'success' : 'error',
          duration: 2000,
        })
      if (res.data.success) {
        dialog.value = false
        getInfo()
      }
    })
  }
  // 获取客户关联商品列表
  const UserRelationCodeGoodsList = ref({ rows: [], total: 0 })
  const getUserRelationCodeGoodsListFun = async () => {
    let data = {
      limit: paginationGoods.value.pageSize,
      page: paginationGoods.value.current,
    }
    loading.value = true
    await getUserRelationCodeGoodsList(data, route.params.id).then((res) => {
      if (res.data.success) {
        UserRelationCodeGoodsList.value = res.data.data
      } else {
        if (res.data.isError)
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 4000,
          })
      }
    })
    loading.value = false
  }
  // 获取客户关联工单列表
  const UserRelationOrderList = ref({ rows: [], total: 0 })
  const getUserRelationOrderListFun = async () => {
    let data = {
      limit: paginationOrder.value.pageSize,
      page: paginationOrder.value.current,
    }
    loading.value = true
    const res = await getUserRelationOrderList(data, route.params.id)
    if (res.data.success) {
      UserRelationOrderList.value = res.data.data
    } else {
      if (res.data.isError)
        ElMessage({
          showClose: true,
          message: res.data.message,
          type: 'error',
          duration: 4000,
        })
    }
    loading.value = false
  }
  const name = ref('') // 客户名称
  const telphone = ref('') // 客户手机号
  const selfData = ref([]) // 联系人列表数据
  const selfDom = ref() // 联系人列表dom

  const paginDom = ref() // 分页dom
  const total = ref() // 总数目

  const fileList = ref([])

  // 获取联系人数据
  const getList = async () => {
    loading.value = true
    const data = {
      limit: paginDom.value.size,
      name: name.value,
      page: paginDom.value.current,
      phone: telphone.value,
    }
    selfData.value = []
    await getUserContact(data, route.params.id).then((res) => {
      selfData.value = res.data.data.rows
      selfData.value.map((item) => {
        item['isEditUserContact'] = false
        item['isMainUser'] = item.mainContact
      })
      total.value = parseInt(res.data.data.total)
    })
    loading.value = false
  }

  // 获取表格选中的数据
  const selecttion = ref([])
  const userContactSelect = ref([])
  const getCheckbox = (val: any[]) => {
    userContactSelect.value = val
    if (val.length != 0) {
      val.forEach((item: { id: any }) => {
        if (Object.values(selecttion.value).indexOf(item.id) == -1) {
          selecttion.value.push(item.id)
        } else {
          selecttion.value = selecttion.value.filter((i) => i == item.id)
        }
      })
    } else {
      selecttion.value = []
    }
  }

  watch(
    () => userContactSelect.value,
    () => {
      userContactBatchDelBtn.value = true
      if (selecttion.value.length > 0) {
        userContactBatchDelBtn.value = false
      }
    },
  )

  // 判断是否可选
  const checkDisable = (row: { mainContact: boolean }) => {
    if (row.mainContact == true) {
      return false // 不可选
    } else {
      return true // 可选
    }
  }

  // 添加行
  const addLineData = () => {
    selfData.value.push({
      username: '',
      phone: '',
      mainContact: false,
      email: '',
      province: '',
      city: '',
      area: '',
      town: '',
      address: '',
      isEditUserContact: true,
    })
  }

  // 删除行
  const deleteLineData = (index: number, obj) => {
    if (obj.id) {
      changeCont('删除', obj, 0)
    } else {
      selfData.value = selfData.value.filter((o, i) => i != index)
    }
  }

  // 编辑联系人
  const onUserContainTableEdit = (obj: any) => {
    obj.isEditUserContact = true
  }

  // 保存联系人
  const onUserContainTableSave = (rowIndex: number, obj: any) => {
    if (!obj.username || obj.username.trim() === '') {
      ElMessage({
        type: 'warning',
        message: `第 ${rowIndex + 1} 行 [联系人姓名] 不能为空`,
      })
      return
    }
    if (!obj.phone) {
      ElMessage({
        type: 'warning',
        message: `第 ${rowIndex + 1} 行 [联系人手机号] 不能为空`,
      })
      return
    }
    if (!/^1[3|4|5|7|8|9]\d{9}$/.test(obj.phone)) {
      ElMessage({
        type: 'warning',
        message: `第 ${rowIndex + 1} 行 [联系人手机号] 格式错误`,
      })
      return
    }
    const addr = addrEditRef.value.getSelectAddr()
    if (!addr.province || addr.province === '') {
      ElMessage({
        type: 'warning',
        message: `第 ${rowIndex + 1} 行 [联系地区] 不能为空`,
      })
      return
    }
    if (!obj.address || obj.address === '') {
      ElMessage({
        type: 'warning',
        message: `第 ${rowIndex + 1} 行 [详细地址] 不能为空`,
      })
      return
    }
    saveContact(obj, addr)
  }

  // 取消编辑
  const onUserContainTableCancel = (rowIndex: number, obj: any) => {
    if (obj.id) {
      obj.isEditUserContact = false
      return
    }
    selfData.value.splice(rowIndex, 1)
  }

  // 保存联系人
  const saveContact = (obj: any, addr: any) => {
    let data = {
      id: obj.id,
      username: obj.username,
      phone: obj.phone,
      mainContact: obj.mainContact,
      province: addr.province,
      city: addr.city,
      area: addr.area,
      town: addr.town,
      address: obj.address,
      email: obj.email,
    }
    loading.value = true
    saveUserContact(data, route.params.id).then((res) => {
      loading.value = false
      if (res.data.isError)
        ElMessage({
          message: res.data.message,
          type: res.data.success ? 'success' : 'error',
          duration: 2000,
        })
      if (res.data.success == true) {
        obj.isEditUserContact = false
        getList()
      }
    })
  }

  // 修改联系人方法
  const changeCont = (type: string, obj: any, num: number) => {
    ElMessageBox({
      type: type == '删除' || type == '批量删除' ? 'error' : 'warning',
      title: '提示',
      icon: markRaw(Delete),
      message: `确认${type}选中的联系人?`,
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      autofocus: false,
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    })
      .then(async () => {
        if (type == '删除') {
          await deleteContact([obj.id]).then((res: any) => {
            ElMessage({
              message: res.data.message,
              type: 'success',
              duration: 2000,
            })
          })
        }
        if (type == '批量删除') {
          await deleteContact(selecttion.value).then((res: any) => {
            ElMessage({
              message: res.data.message,
              type: 'success',
              duration: 2000,
            })
          })
        }
        if (type == '更改') {
          changeContact(obj.id, route.params.id).then((res) => {
            ElMessage({
              message: res.data.message,
              type: 'success',
              duration: 2000,
            })
          })
        }
        selfDom.value.clearSelection()
        getList()
      })
      .catch(() => {
        if (num == 1) {
          obj.mainContact = !obj.mainContact
        }
      })
  }

  // 批量删除联系人
  const deleAll = () => {
    if (selecttion.value.length == 0) {
      ElMessage({
        message: `请选择要删除的联系人`,
        type: 'warning',
        duration: 2000,
      })
      return
    }
    changeCont('批量删除', '', 1)
  }

  // 上传附件
  const handleChange: UploadProps['onChange'] = (uploadFile: UploadFile) => {
    let { name } = uploadFile.raw
    let tmp = {
      id: null,
      name,
      path: window.URL.createObjectURL(uploadFile.raw),
      file: uploadFile.raw,
    }
    fileList.value.push(tmp)
  }

  // 删除附件
  const deleteItem = (index: number) => {
    fileList.value = fileList.value.filter((o, i) => {
      if (o.id && i == index) {
        delAnnexIds.value.push(o.id)
      }
      return i != index
    })
  }
  // 查看图片
  const file = ref({ file: null, type: '' }) //文件
  const dialogContract = ref(false) //文件查看弹窗
  const lookFile = (val, type) => {
    file.value = { file: val, type: type }
    dialogContract.value = true
  }
  // 根据客户ID获取客户附件
  const getUserFilt = async () => {
    loading.value = true
    await getUserAnnex(route.params.id).then((res) => {
      if (res.data.success) {
        fileList.value = res.data.data.row
      } else {
        if (res.data.isError)
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            duration: 4000,
          })
      }
    })
    loading.value = false
  }
  // 取消
  const onCancel = () => {
    getUserFilt()
    delAnnexIds.value = []
  }
  // 保存附件
  const annexSaveSubmit = _.debounce(async () => {
    let data = {
      annexVos: [],
      delAnnexIds: delAnnexIds.value,
    }
    let img = [] //已经上传过的
    let imgNew = [] //新上传的
    fileList.value.filter((o) => {
      if (o.id) {
        img.push(o)
      } else {
        imgNew.push(o.file)
      }
    })
    // 判断是否有新上传图片附件
    if (imgNew.length > 0) {
      await userAnnexUpload(imgNew).then((res) => {
        imgNew = res.data.data.rows.map((o) => {
          return { id: null, path: o }
        })
      })
    } else {
      if (delAnnexIds.value.length == 0) {
        ElMessage({
          showClose: true,
          message: '请选择要上传的图片附件！',
          type: 'error',
          duration: 4000,
        })
        return
      }
    }
    data.annexVos = [...img, ...imgNew]
    await annexSave(data, route.params.id).then((res) => {
      if (res) {
        if (res.data.code == 20000) {
          getUserFilt()
          delAnnexIds.value = []
          ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'success',
            duration: 3000,
          })
        } else {
          if (res.data.isError)
            ElMessage({
              showClose: true,
              message: res.data.message,
              type: 'error',
              duration: 4000,
            })
        }
      }
    })
  }, 600)
</script>

<style scoped lang="scss">
  @import './index.scss';
</style>
